import React, { Component } from 'react';
import { Form, Modal, Input, Button, Select, Radio, } from 'antd'
import { QuestionOutlined } from '@ant-design/icons';
import TheTable from "../../../components/TheTable";
import TheButton from "../../../components/TheButton";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '../../../components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import { apiGetBrandinfoList, apiGetGoodsClassifyTree } from '@/request/mallManagement'

const { Option } = Select
class AppBrandInfo extends Component {
    constructor() {
        super()
        this.queryFormRef = React.createRef()
        this.formRef = React.createRef()
        this.formRefAnalyze = React.createRef()
        this.state = {
            title: '新增',
            loading: false,
            dataSource: [],
            columns: [
                {
                    title: "关键词",
                    dataIndex: "keyword",
                    key: "keyword"
                },
                {
                    title: "关键词状态",
                    dataIndex: "keywordStatus",
                    key: "keywordStatus",
                    render: (text, render) => {
                        return text === 0 ? "开启" : "关闭"
                    }
                },
                {
                    title: "操作",
                    render: (text, record) => {
                        return <>
                            <TheButton haspermi={[]} onClick={() => this.edit(record)}>编辑</TheButton>
                            <TheButton haspermi={[]} onClick={() => this.del(record.id)}>删除</TheButton>
                        </>
                    }
                },
            ],
            newColumns: [],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: 0,
            brandList: [],
            brandInfo: {},
            isModalOpen: false,
            form_show: true,
            searchOption: [
                { field: 'keyword', label: '关键词', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
            ],
            queryForm: {},
            isEdit: false,
            classifyList: [],
            isanalyzeTest: false,
            analyzeTestData: [],
            analyzeTestColumns: [
                {
                    title: "分词",
                    dataIndex: "term",
                    key: "term"
                },
                {
                    title: "分词类型",
                    dataIndex: "type",
                    key: "type"
                },
            ],
        }
    }
    async componentDidMount() {
        this.getData()
        this.getClassifyList()
        this.onColumnsFilter(this.state.columns)
    }
    async getClassifyList() {
        const res = await apiGetGoodsClassifyTree()
        if (res.code === 0) {
            this.setState({
                classifyList: res.data.map((v) => {
                    return {
                        value: v.value,
                        label: v.label,
                        children: v.children.length > 0 ? v.children : []
                    }
                })
            })
        }
    }
    classifyChange = (e) => {
        this.getBrandList(e[e.length - 1])
    }
    async getBrandList(e) {
        let res = await apiGetBrandinfoList({ brandClassifyId: e })
        if (res.code === 0) {
            if (this.formRef.current && !this.state.isEdit) {
                this.formRef.current.setFieldsValue({
                    brandId: ''
                })
            }

            this.setState({
                brandList: res.data
            })
        }
    }
    getData(values) {
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            const { pageNo, pageSize } = this.state.pageData
            const { queryForm } = this.state
            const res = await React.$post("/admin/analyzeDict/page", { pageNo, pageSize, ...queryForm })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })
    }
    add() {
        this.setState({
            isEdit: false,
            isModalOpen: true,
            title: '新增'
        })
    }
    handleOk = async () => {
        const values = this.formRef.current.getFieldsValue()
        const { id } = this.state.brandInfo
        if (this.state.isEdit) {
            const res = await React.$post("/admin/analyzeDict/edit", { id, keyword: values.keyword, keywordStatus: values.keywordStatus })
            if (res.code === 0) {
                this.handleCancel()
                this.getData()
            }
        } else {
            const res = await React.$post("/admin/analyzeDict/add", { ...values })
            if (res.code === 0) {
                this.handleCancel()
                this.pageChange(1, 10)
            }
        }
    };
    handleCancel = () => {
        this.formRef.current.resetFields()
        this.setState({
            isModalOpen: false,
            brandList: []
        })
    };
    async edit(row) {
        this.setState({
            isEdit: true,
            isModalOpen: true,
            title: '编辑',
            brandInfo: { ...row },
            couponType: row.keywordStatus
        }, () => {
            this.formRef.current.setFieldsValue({
                Id: row.id,
                keyword: row.keyword,
                keywordStatus: row.keywordStatus
            })
        })
    }
    del = record => {
        React.$confirm({
            title: "警告",
            content: `确定删除此信息吗？`,
            onOk: async () => {
                const res = await React.$post("/admin/analyzeDict/del", { id: record })
                if (res.code === 0) {
                    this.pageChange(1, 10)
                }
            }
        });
    }
    analyzeTestOk = async () => {
        const values = this.formRefAnalyze.current.getFieldsValue()
        const res = await React.$post("/admin/analyzeDict/analyzeTest", { ...values })
        if (res.code === 0) {
            this.setState({
                analyzeTestData: res.data.tokens
            })
        }
    };
    analyzeTestCancel = () => {
        this.setState({
            isanalyzeTest: false
        })
    }
    pageChange = (pageNo, pageSize) => {
        console.log(pageNo, pageSize);
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => {
            this.getData()
        })
    }
    onTableRefresh() {
        this.getData()
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    reconstitution = () => {
        React.$confirm({
            title: "警告",
            content: (<p>请确认需要加的关键词已经可以在测试分词中从同类型的字符中分出该词语<br /><br />确定进行索引重构？</p>),
            onOk: async () => {
                let res = await React.$post("/admin/analyzeDict/reindex")
                if (res.code === 0) {
                    React.$message({
                        type: 'info',
                        content: '重构索引成功！'
                    })
                }
            }
        });
    }
    help = () => {
        Modal.info({
            title: "提示",
            content: (<p>步骤1: 新增关键词 <br />
                新增需要根据该关键词，在app中搜索出商品的字符。<br />
                步骤2: 刷新扩展词典缓存 <br />
                刷新后稍稍等待。  <br />
                步骤3: 测试分词 <br />
                输入字符中包含该分词的短句。<br />
                注意需要起始或者结尾连接处的字符类型跟原字符类型一致，<br />
                否则就分辨不出到底能不能分出来了。 <br />
                例 关键词:abc 短句:abcd 结果: abcd,abc 把abc从abcd中分出来了。<br />
                步骤4: 重构索引 <br />
                新建一个索引库把老库的数据填充到新库中需要一定时间所以加上最小时间的限制以实际为准。</p>),
            okText: '知道了',
        });
    }
    reflushAll = async () => {
        let res = await React.$post("/admin/analyzeDict/flushAll")
        if (res.code === 0) {
            React.$message({
                type: 'info',
                content: '刷新索引成功！'
            })
        }
    }
    analyzeTest = async (word) => {
        this.setState({
            isanalyzeTest: true
        })
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    brandChange(e) {
        const { brandList } = this.state
        this.setState({
            brandInfo: brandList.find(item => item.brandId === e)
        })
    }
    render() {
        const { isEdit, brandList, classifyList, brandInfo, loading, dataSource, columns, pageData, total, newColumns, isModalOpen, form_show, title, fileList, searchOption, isanalyzeTest, analyzeTestColumns, analyzeTestData, couponType } = this.state
        const { pageNo, pageSize } = pageData
        return (
            <div className={"p-layout-box configuration"}>
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption} onGetValues={(values) => this.getData(values)}
                    onReset={(values) => this.onReset(values)} >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.onTableRefresh()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton type={'primary'} size={'middle'} haspermi={['set:analyzeDict:Add']}
                        onClick={() => { this.add() }}>新增关键词
                    </TheButton>
                    <TheButton type={'primary'} size={'middle'} haspermi={['set:analyzeDict:flushAll']}
                        onClick={() => { this.reflushAll() }}>刷新索引
                    </TheButton>
                    <TheButton type={'primary'} size={'middle'} haspermi={['set:analyzeDict:analyzeTest']}
                        onClick={() => { this.analyzeTest() }}>测试分词
                    </TheButton>
                    <TheButton type={'primary'} size={'middle'} haspermi={['set:analyzeDict:reconstitution']}
                        onClick={() => { this.reconstitution() }}>重构索引
                    </TheButton>
                    <TheButton type={'default'} size={'middle'} haspermi={[]} shape="circle" icon={<QuestionOutlined />}
                        onClick={() => { this.help() }}>
                    </TheButton>
                </TheTableExtend>

                <TheTable bordered loading={loading} dataSource={dataSource} columns={newColumns} />
                <ThePagination pageNo={pageNo} pageSize={pageSize} total={total}
                    pageChange={this.pageChange}
                />
                <Modal title={title} visible={isModalOpen} footer={null} onOk={() => this.handleOk()} onCancel={() => this.handleCancel()}>
                    <Form ref={this.formRef}
                        onFinish={(values) => this.handleOk(values)}
                        labelCol={{
                            span: 8,
                        }}
                        wrapperCol={{
                            span: 12,
                        }}
                    >
                        <Form.Item
                            name="keyword"
                            label='关键词'
                            rules={[{ required: true }]}>
                            <Input />
                        </Form.Item>
                        {title === "新增" ? null :
                            <Form.Item
                                name="keywordStatus"
                                label='关键词状态'
                                rules={[{ required: true }]}>
                                <Radio.Group defaultValue={couponType}>
                                    <Radio value={0}>开启</Radio>
                                    <Radio value={1}>关闭</Radio>
                                </Radio.Group>
                            </Form.Item>
                        }
                        <Form.Item
                            wrapperCol={{
                                offset: 8,
                                span: 16,
                            }}
                        >
                            <Button type="default" onClick={() => this.handleCancel()} style={{ 'marginRight': 20 }}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal title={"测试分词"} visible={isanalyzeTest} footer={null} onOk={() => this.analyzeTestOk()} onCancel={() => this.analyzeTestCancel()}>
                    <div style={{ marginBottom: "10px" }}>
                        <Form ref={this.formRefAnalyze}
                            layout="inline"
                            onFinish={(values) => this.analyzeTestOk(values)}
                            labelCol={{
                                span: 8,
                            }}
                            wrapperCol={{
                                span: 16,
                            }}
                        >
                            <Form.Item
                                name="word"
                                label='关键词'
                                rules={[{ required: true }]}>
                                <Input />
                            </Form.Item>
                            <Button type="primary" htmlType="submit">
                                搜索
                            </Button>
                        </Form>
                    </div>
                    <TheTable bordered dataSource={analyzeTestData} columns={analyzeTestColumns} />
                </Modal>
            </div>
        )
    }
}

export default AppBrandInfo